﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Kwik.Orm
{
	/// <summary>
	/// Database table object 
	/// </summary>
	public sealed class Table : ISchemaTable, IXmlSerializable
	{
		/// <summary>
		/// Create a new table object
		/// </summary>
		public Table() { }
		/// <summary>
		/// Create a new table object with the supplied name
		/// </summary>
		/// <param name="name">Table name</param>
		public Table(string name) { this.Name = name; }

		private readonly IDictionary<string, ISchemaColumn> _Columns = new Dictionary<string, ISchemaColumn>();
		private readonly IDictionary<string, ISchemaConstraint> _Constraints = new Dictionary<string, ISchemaConstraint>();

		/// <summary>
		/// Table name
		/// </summary>
		public string Name { get; set; }
		/// <summary>
		/// Table description
		/// </summary>
		public string Description { get; set; }
		/// <summary>
		/// Collections of columns by name
		/// </summary>
		public IDictionary<string, ISchemaColumn> Columns { get { return _Columns; } }
		/// <summary>
		/// Collections of constraints by name
		/// </summary>
		public IDictionary<string, ISchemaConstraint> Constraints { get { return _Constraints; } }

		#region IXmlSerializable Members

		public System.Xml.Schema.XmlSchema GetSchema()
		{
			throw new NotImplementedException();
		}

		public void ReadXml(System.Xml.XmlReader reader)
		{
			throw new NotImplementedException();
		}

		public void WriteXml(System.Xml.XmlWriter writer)
		{
			XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
			ns.Add("", "");

			XmlSerializer columnSerializer = new XmlSerializer(typeof(Column));
			XmlSerializer constraintSerializer = new XmlSerializer(typeof(Constraint));

			writer.WriteAttributeString("Name", this.Name);
			if(!string.IsNullOrEmpty(this.Description))writer.WriteAttributeString("Description", this.Name);

			writer.WriteStartElement("Columns");
			foreach (Column column in this.Columns.Values)columnSerializer.Serialize(writer, column, ns);
			writer.WriteEndElement();

			writer.WriteStartElement("Constraints");
			foreach (Constraint constraint in this.Constraints.Values) constraintSerializer.Serialize(writer, constraint, ns);
			writer.WriteEndElement();
		}

		#endregion
	}
}
